﻿package Cain.editor
{
	import flash.display.Sprite;
	import Cain.editor.Sc_editer;
	import flash.events.Event;
	import flash.events.MouseEvent;
	/**
	 * 物件編輯系統 v1.1 2010.11.3
	 * @author Cain@2009 in ADCAST
	 */
	public class MC_editor 
	{
		private var mv:Sprite;
		private var der_arr:Array = new Array();
		private var mc_name_arr:Array = new Array();
		private var now_de:Sc_editer = null;
		/**
		 * 	編輯系統初始化
		 * @param	_mv 場景容器
		 */
		public function MC_editor(_mv:Sprite) 
		{
			mv = _mv;
			init();
		}
		
		private function init():void
		{
			mc_name_arr_init();
			var num:int = mv.numChildren;
			for (var i:int = 0; i < num; i++) 
			{
				var mc:Sprite = Sprite(mv.getChildByName(mc_name_arr[i]));
				var der:Sc_editer = new Sc_editer(mc);
				der_arr.push(der);
			}
			der_start();
		}
		
		private function mc_name_arr_init():void
		{
			for (var i:int = 0; i < mv.numChildren; i++) 
			{
				mc_name_arr.push(mv.getChildAt(i).name);
			}
		}
		
		private function der_start():void
		{
			if (mv.stage !=null) 
			{
				mv.stage.addEventListener(MouseEvent.MOUSE_DOWN, selet);
			}else 
			{
				mv.addEventListener(Event.ADDED_TO_STAGE, onADDED_TO_STAGE);
			}
			
		}
		
		private function onADDED_TO_STAGE(e:Event):void 
		{
			
			mv.addEventListener(Event.REMOVED_FROM_STAGE, onREMOVED_FROM_STAGE);
			mv.stage.addEventListener(MouseEvent.MOUSE_DOWN, selet);
		}
		
		private function onREMOVED_FROM_STAGE(e:Event):void 
		{
			mv.stage.removeEventListener(MouseEvent.MOUSE_DOWN, selet);
			mv.removeEventListener(Event.REMOVED_FROM_STAGE, onREMOVED_FROM_STAGE);
		}
		
		private function selet(e:MouseEvent):void 
		{
			var sel:int = 0;
			for (var i:int = 0; i < der_arr.length; i++) 
			{
				if (e.target.name!="sc_editer_bb_point") 
				{
					if (e.target.name == der_arr[i]._mc.name) 
					{
						sel++;
						der_arr[i].bb_ed();
						mv.addChild(mv.getChildByName(mc_name_arr[i]));
						now_de = der_arr[i];
					}else{
						der_arr[i].bb_ud();
					}
				}
			}
			if (sel==0) 
			{
				now_de = null;
			}
		}
		/**
		 * 增加編輯物件
		 * @param	mc
		 */
		public function addmc(mc:Sprite):void 
		{
			mc_name_arr.push(mc.name);
			var der:Sc_editer = new Sc_editer(mc);
			der_arr.push(der);
		}
		/**
		 * 刪除編輯物件
		 */
		public function delmc():void 
		{
			if (now_de!=null) 
			{
				now_de.unload();
			}
		}
	}
	
}